<?php

// optional output=screen will return results to text area
// Error if we don't have a Project ID and Crudset ID
//Incluce DB connect 
include_once "quickcrud_connect.php";
include_once "quickcrud_common.php";
include_once "quickcrud_common.php";
//include_once "commonctls.php";
include_once "CF_mysql_com.php";
include_once "CF_all_com.php";


if (!isset($_REQUEST['crudset_id']) OR !isset($_REQUEST['project_id'])){
	print 'Please Select a project and display set (crudset)';
    exit;
}

$crudset_id = $_REQUEST['crudset_id'];
$project_id = $_REQUEST['project_id'];

$fieldspec = make_fields_spec($crudset_id);

if($_REQUEST['output'] == 'screen'){
// Displays to textarea on screen
echo "<html>\n<head>\n</head>\n<body>";
echo "<TEXTAREA NAME=\"comments\" COLS='80' ROWS='20'>$fieldspec</TEXTAREA>\n";
echo "</body></html>";

}
else{
$project_path = lookup_value('project_path', 'projects', "project_id = $project_id");
$cs_name = lookup_value('cs_name', 'crudsets', "crudset_id = $crudset_id");
$subdirectory = lookup_value('subdirectory', 'crudsets', "crudset_id = $crudset_id");

// if subdirectory path not exists, create
if(!empty($subdirectory)){
	$subdirname = rtrim($subdirectory, "/");
		if(!file_exists('projects/' . $project_path . "/" . WEBAPP_SUBPATH . '/' . $subdirname))
		{
			mkdir('projects/' . $project_path . "/" . WEBAPP_SUBPATH . '/' . $subdirname);
		}
	}


$output_file = PROJECT_SUBPATH . $project_path . '/' . WEBAPP_SUBPATH . '/' . $subdirectory . $cs_name . '_fields.php';
//print $output_file;
$result = "Wrote Fields To $output_file";
$result = urlencode($result);
file_put_contents($output_file,"<?php \n" . $fieldspec . "\n?>");
        $header_text = "Location: leftmenu.php?project_id=$project_id&crudset_id=$crudset_id&result=$result";
        header($header_text); /* Redirect browser */
        exit;
 }

function make_fields_spec($crudset_id){
	// get crudcolums for that crudset and project
	$qry_get_columns = "SELECT * FROM crudcols WHERE crudset_id = $crudset_id ORDER BY col_order ";
	$list_array = get_mysql_array($qry_get_columns);

	// make standard settings description
	$start_str .="
// ----------------------------- Field Spec settings are as below:	
//\$fieldspec['<column>'] ['show'] = {'0' = notshown, '1' = show readonly, 'L' = show, use list (manual join), E = editable;
//\$fieldspec['<column>'] ['key'] = {1 = key field, 0 of not (or dont include)};
//\$fieldspec['<column>'] ['select'] = {'T' = text, 'D' = dropdown select, 'C' = checkbox (for 1 or 0 boolean), 'R' = radiogroup, 'A' = textarea, 'DT' = calendar for date-time};
//\$fieldspec['<column>'] ['filter'] = {1 if value is filtered for, 0 or undefined if not};	
//\$fieldspec['<column>'] ['add'] = {1 = include value as input in add box, 0 or undefined = do not };
//\$fieldspec['<column>'] ['size'] = size of input field, or columns (cols) for textarea;
//\$fieldspec['<column>'] ['rows'] = rows of textarea or listbox (future);
//\$fieldspec['<column>'] ['headname'] = {Name to show on column heading or input heading};
//\$fieldspec['<column>'] ['keyvalue'] = {array column to use for key in drop-down lists} ;
//For lists, Not needed if columns 'keyvalue' and 'showvalue' are used in array, no need to define these specs;
//\$fieldspec['<column>'] ['showvalue'] = {array column to use for shown value in drop-down lists};
//\$fieldspec['<column>'] ['rawformat']	= additional html to include inside the input field;
//\$fieldspec['<column>'] ['image']	= image file name of image to associate with control (implemetned for calendar);
//\$fieldspec['<column>'] ['showdateformat'] = format string for inital display of shown date, using php date formatters;
//\$fieldspec['<column>'] ['cal'] ['ifFormat'] = format string of date from database (or whatever) for input to calendar, js date formatters;
//\$fieldspec['<column>'] ['cal'] ['align'] = {'T1' Shows calendar above imput control (default), 'B1' shows it below controls};
//\$fieldspec['<column>'] ['cal'] ['showsTime'] = {true = show time in calendar below date, false (Default) = show and use calendar for dates only};
//\$fieldspec['<column>'] ['cal'] ['singleClick'] = {true = (Default) open calendar with single click, false = double click for calendar};
//\$fieldspec['<column>'] ['allowhtml'] = {true:  do not escape html (to allow images, etc), false (or unset by default) escapes using htmlspecialchars)};
//\$fieldspec['<column>']['source'] = table name for source table, will be appended to filters to resolve ambiguies with multiple tables
//\$fieldspec['<column>']['makefunction'] = construct function - function to call to create the field from the data (defaults to the col_name, make_colname)


//---Note - for autoheadings, rows will be arranged in the order of these definition secitons for each column
	";
	
	
	
	
	foreach ($list_array as $rowkey => $currentrow){
		$variable_id = $currentrow['variable_id'];
		$variable_name = lookup_value('variable_name', 'variables', "variable_id = $variable_id");
		$fields_str .= "\n//column settings for $variable_name\n";

		// show
		$edit_in_list = $currentrow['edit_in_list'];
        $shown_in_list = $currentrow['shown_in_list'];
        if($shown_in_list != 0){
               // $qry_list = $currentrow['list_query'];
            if($edit_in_list != 0){
                $fields_str .= "\$fieldspec['$variable_name'] ['show'] = 'E';\n";
              }
            //  prior if must be first (excusivity not enforced)
            else if(($currentrow['edit_type'] == 'querylist') OR ($currentrow['edit_type'] == 'commalist')){
                $fields_str .= "\$fieldspec['$variable_name'] ['show'] = 'L';\n";
               }
            else{
                $fields_str .= "\$fieldspec['$variable_name'] ['show'] = $shown_in_list;\n";
             }
        } // end shown
		
		// is_key -> ['key'] spec
		if($currentrow['is_key'] == 1){
			$fields_str .= "\$fieldspec['$variable_name'] ['key'] = 1;\n";
		}

		if(!empty($currentrow['is_add'])){
			$fields_str .= "\$fieldspec['$variable_name'] ['add'] = " . $currentrow['is_add'] . ";\n";
		}
		
		// lookup query
		if($currentrow['edit_type'] == 'querylist'){
			$fields_str .= "\$fieldspec['$variable_name'] ['select'] = 'D';\n";
			if(!empty($currentrow['list_query'])){
				//$fields_str .= "\$array_" . $variable_name . "_list = get_array_query(\"" . $currentrow['list_query'] . "\");\n";
				// CT Added this to seperate section for LIST pages only
	
				$list_fields_str .= "\$array_" . $variable_name . "_list = get_array_query(\"" . $currentrow['list_query'] . "\");\n";
			
				$fields_str .= "\$fieldspec['$variable_name'] ['list'] = \$array_" . $variable_name . "_list;\n";
			}			
			if(!empty($currentrow['list_keycol'])){
				$fields_str .= "\$fieldspec['$variable_name'] ['keyvalue'] = '{$currentrow['list_keycol']}';\n";
					
			}
			if(!empty($currentrow['list_showcol'])){
				$fields_str .= "\$fieldspec['$variable_name'] ['showvalue'] = '{$currentrow['list_showcol']}';\n";
				}			
		} // end list

        // lookup list
      if($currentrow['edit_type'] == 'commalist'){
          $list_string = $currentrow['list_query'];
          $commalist_array = explode(',',$list_string);
          $list_array_count = 1;
          foreach ($commalist_array as $list_element){
              $fields_str .= "\$array_" . $variable_name . "_list [$list_array_count] ['keyvalue'] = '$list_element';\n";
              $fields_str .= "\$array_" . $variable_name . "_list [$list_array_count] ['showvalue'] = '$list_element';\n";
              $list_array_count ++;
              } // end for each comma list
 		$fields_str .= "\$fieldspec['$variable_name'] ['list'] = \$array_" . $variable_name . "_list;\n";
      }

      if(!empty($currentrow['header_name'])){
          $fields_str .= "\$fieldspec['$variable_name'] ['headname'] = '" .  $currentrow['header_name'] . "';\n";  
          }

      // If editable
      if($edit_in_list != 0){
          if($currentrow['edit_type'] == 'commalist'){
                $fields_str .= "\$fieldspec['$variable_name'] ['select'] = 'D';\n";
            } else if($currentrow['edit_type'] == 'text'){
                $fields_str .= "\$fieldspec['$variable_name'] ['select'] = 'T';\n";
            } else if($currentrow['edit_type'] == 'checkbox'){
                $fields_str .= "\$fieldspec['$variable_name'] ['select'] = 'C';\n";
            } else if($currentrow['edit_type'] == 'textarea'){
                $fields_str .= "\$fieldspec['$variable_name'] ['select'] = 'A';\n";
            } else if($currentrow['edit_type'] == 'calendar'){
                $fields_str .= "\$fieldspec['$variable_name'] ['select'] = 'DT';\n";
            } else if($currentrow['edit_type'] == 'calicon'){
                $fields_str .= "\$fieldspec['$variable_name'] ['select'] = 'CAL';\n";
            } else if($currentrow['edit_type'] == 'multical'){
                $fields_str .= "\$fieldspec['$variable_name'] ['select'] = 'MCAL';\n";
            }		
          }

		// is_filter -> ['filter'] spec
		if(!empty($currentrow['filter'])){
			$fields_str .= "\$fieldspec['$variable_name'] ['filter'] = " . $currentrow['filter'] . ";\n";
		}		

		// is_showfilter-> ['showfilter'] spec
		if($currentrow['showfilter'] == 1){
			$fields_str .= "\$fieldspec['$variable_name'] ['showfilter'] = 1;\n";
		}			
		
		// is_sort -> ['sort'] spec
		if($currentrow['is_sort'] == 1){
			$fields_str .= "\$fieldspec['$variable_name'] ['sort'] = true;\n";
		}			

        // set size
        if(!empty($currentrow['size'])){
            $fields_str .= "\$fieldspec['$variable_name'] ['size'] = " . $currentrow['size'] . ";\n";
            }
        // set rows
        if(!empty($currentrow['rows'])){
            $fields_str .= "\$fieldspec['$variable_name'] ['rows'] = " . $currentrow['rows'] . ";\n";
            }
		
		if(!empty($currentrow['makefunction'])){
            $fields_str .= "\$fieldspec['$variable_name'] ['makefunction'] = '" . $currentrow['makefunction'] . "';\n";			
		}
		
	}// end foreach row in crudcols list
	
	
	// produce list_fields_str with check for list pages only
	
	$list_fields_str = "\nif((\$PAGETYPE == 'LIST') OR (\$PAGETYPE == 'FORM') ){\n" . $list_fields_str;
	$list_fields_str .= "\n}\n";
	
	
	return $start_str . $list_fields_str . $fields_str;
}// end function

?>